package fractal;

import jinyilw.common.ArrayTools;
import jinyilw.swing.ColorTools;

import java.awt.Color;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;

public class FractalColor
{
	private static final int NLength = 800;
	private static final int GLength = 200;
	private static final int FLength = 300;
	private static int[] normalColorSpace;
	private static int[] gradualColorSpace;
	private static int[] fullColorSpace;
	private static Color[] gradualColors;

	private static int getRGB(int n)
	{
		int red = n * 2 + 20, grn = n * 3 + 105, blu = n * 4 + 255;
		if ((red & 0x1FF) > 0xFF)
			red = red ^ 0xFF;
		if ((grn & 0x1FF) > 0xFF)
			grn = grn ^ 0xFF;
		if ((blu & 0x1FF) > 0xFF)
			blu = blu ^ 0xFF;
		return 0xff << 24 | red << 16 | grn << 8 | blu;
	}

	public static int[] getNormalColorSpace()
	{
		if (normalColorSpace == null)
		{
			normalColorSpace = new int[NLength];
			for (int i = 0; i < NLength; i++)
				normalColorSpace[i] = getRGB(i);
		}
		return normalColorSpace;
	}

	public static int[] getGradualColorSpace(Color[] colors)
	{
		if (gradualColorSpace == null)
			gradualColorSpace = new int[GLength];

		if (colors != null && !Arrays.equals(colors, gradualColors))
		{
			ColorTools.calculateCircleGradualRGBs(gradualColorSpace, colors[0],
					colors[1], colors[2], colors[3]);
			ArrayTools.copy(colors, gradualColors);
		}
		return gradualColorSpace;
	}

	public static int[] getFullColorSpace()
	{
		if (fullColorSpace == null)
		{
			fullColorSpace = new int[FLength];
			ColorTools.createFullColorRGBs(fullColorSpace, FLength);
		}
		return fullColorSpace;
	}

	public static int[] getFractalColorSpace(int type, Color[] gradualColors)
	{
		switch (type)
		{
			case 0:
				return getNormalColorSpace();
			case 1:
				return getGradualColorSpace(gradualColors);
			case 2:
				return getFullColorSpace();
		}
		return getNormalColorSpace();
	}

	public static int[] getColorSpace(File f)
	{
		int[] colorSpace = new int[NLength];
		int size;
		int[] rgbs;
		try
		{
			DataInputStream dis = new DataInputStream(new FileInputStream(f));
			size = dis.readInt();
			rgbs = new int[size];
			for (int i = 0; i < size; i++)
				rgbs[i] = dis.readInt();
			dis.close();
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		for (int i = 0; i < colorSpace.length; i++)
			colorSpace[i] = rgbs[i % size];
		return colorSpace;
	}
}
